package com.jctf.net;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class SequenceServer implements MessageListener {

	private NetworkManager n;
	private static int PORT = 33962;
	
	@Override
	public void messageReceived(Message message) {
		System.out.println("Message received: " + message);
	}

	public static void main(String[] args) {
		try {
			new SequenceServer().run();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run() throws IOException {
		System.out.println("Starting server...");
		n = new NetworkManager();
		n.registerMessageListener(this);
		n.start();
	}

	private class NetworkManager extends NetworkHandler {

		private ServerSocket server;
		private ArrayList<Socket> connections = new ArrayList<Socket>();
		private ArrayList<ObjectOutputStream> output = new ArrayList<ObjectOutputStream>();
		private ArrayList<ObjectInputStream> input = new ArrayList<ObjectInputStream>();
		private Hermes messenger;
		
		@Override
		public void registerMessageListener(MessageListener l) {
			System.out.println("Registered server as listener...");
			listeners.add(l);
		}
		
		public void start() throws IOException {
			server = new ServerSocket(PORT, 6);
			messenger = new Hermes();
			messenger.start();
			while(true) {
				Socket s = server.accept();
				System.out.println("Connection made!");
				connections.add(s);
				output.add(new ObjectOutputStream(s.getOutputStream()));
				input.add(new ObjectInputStream(s.getInputStream()));
			}
		}
		
		public void close() throws IOException {
			for(Socket s : connections)
				s.close();
			server.close();
		}
		
		private class Hermes extends Thread {
			
			@Override
			public void run() {
				boolean run = true;
				while(run) {
					for(int i = 0; i < connections.size(); i++) {
						try {
							Object message = input.get(i).readObject();
							if(message instanceof RequestLoginMessage)
								System.out.println("Login request received from " + connections.get(i).getInetAddress());
							else if (message instanceof NumberMessage)
								System.out.println(connections.get(i).getInetAddress() + ": " + (NumberMessage) message);
						} catch (EOFException e) {
							System.out.println("Client quit!");
							connections.remove(i);
							output.remove(i);
							input.remove(i);
							continue;
						} catch (IOException e) {
							e.printStackTrace();
						} catch (ClassNotFoundException e) {
							e.printStackTrace();
						}
					}
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				
			}
		}
		
	}
	
}